<template>
  <div class="p-6 flex gap-4" style="height: calc(100vh - 120px);">
    <!-- 左侧答卷列表 -->
    <el-card class="flex flex-col" style="flex: 0 0 30%; overflow-y: auto;">
      <h3 class="text-lg font-bold mb-4">学生答卷列表</h3>
      <el-table
        :data="paperList"
        style="flex: 1;"
        height="100%"
        highlight-current-row
        @row-click="selectPaper"
        :row-key="row => `${row.studentId}-${row.paperId}`"
        :current-row="selectedPaper"
        empty-text="暂无答卷"
      >
        <el-table-column prop="studentName" label="学生姓名" />
        <el-table-column prop="paperName" label="试卷名称" />
        <el-table-column prop="createTime" label="提交时间" width="180" />
      </el-table>
    </el-card>

    <!-- 右侧批改区 -->
    <el-card class="flex flex-col" style="flex: 1; overflow-y: auto;">
      <template v-if="selectedPaperDetail">
        <h2 class="text-xl font-bold mb-4">
          试卷：{{ selectedPaperDetail.paperName }}（ 学生： {{ selectedPaperDetail.studentName }}）
        </h2>

        <!-- 循环题目 -->
        <template v-if="selectedPaperDetail.answerList && selectedPaperDetail.answerList.length">
          <div
            v-for="(item, idx) in selectedPaperDetail.answerList"
            :key="idx"
            class="mb-6"
          >
            <p class="font-semibold">{{ idx + 1 }}. {{ item.title }}</p>
            <p class="mb-2 text-gray-600">学生答案：{{ item.answer }}</p>

            <el-input-number
              v-model="grading[idx].score"
              :min="0"
              :max="10"
              label="得分"
              class="mb-2"
              style="width: 100px;"
            />
            <el-divider />
          </div>
        </template>

        <!-- 总评放在最后 -->
        <el-input
          v-model="overallComment"
          type="textarea"
          :rows="2"
          placeholder="老师评语"
          class="mb-4"
        />

        <div>
          <el-button type="primary" @click="submitGrading" :loading="submitting">
            提交批改
          </el-button>
        </div>
      </template>

      <el-empty v-else description="请选择一份答卷查看详情" />
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  getPaperSubmissions,
  getPaperSubmissionDetail,
  submitGradingResult,
} from "../api/answer";

const paperList = ref([]);
const selectedPaper = ref(null);
const selectedPaperDetail = ref(null);
const grading = ref([]);
const submitting = ref(false);
const overallComment = ref(""); // 老师总评

// 获取答卷列表
const fetchPaperList = async () => {
  try {
    const res = await getPaperSubmissions();
    if (res.code === 200) {
      paperList.value = res.data || [];
    } else {
      ElMessage.error(res.message || "获取答卷列表失败");
    }
  } catch (err) {
    ElMessage.error("获取答卷列表失败");
  }
};

// 选择某份答卷
const selectPaper = async (row) => {
  selectedPaper.value = row;
  selectedPaperDetail.value = null;
  grading.value = [];
  overallComment.value = "";

  try {
    const res = await getPaperSubmissionDetail({
      studentName: row.studentName,
      paperId: row.paperId,
    });

    if (res.code === 200) {
      selectedPaperDetail.value = res.data;
      grading.value =
        res.data.answerList?.map(() => ({
          score: 0,
        })) || [];
    } else {
      ElMessage.error(res.message || "获取答卷详情失败");
    }
  } catch {
    ElMessage.error("获取答卷详情失败");
  }
};

// 提交批改
const submitGrading = async () => {
  if (!selectedPaperDetail.value) return;

  // 计算总分
  const totalScore = grading.value.reduce(
    (sum, g) => sum + (Number(g.score) || 0),
    0
  );

  submitting.value = true;
  try {
    const payload = {
      id: selectedPaperDetail.value.id,
      studentId: selectedPaperDetail.value.studentId,
      paperId: selectedPaperDetail.value.paperId,
      studentName: selectedPaperDetail.value.studentName,
      paperName: selectedPaperDetail.value.paperName,
      totalScore, // ✅ 总分
      overallComment: overallComment.value, // ✅ 老师总评
      createTime: selectedPaperDetail.value.createTime,
      updateTime: selectedPaperDetail.value.updateTime || "",
    };

    const res = await submitGradingResult(payload);
    if (res.code === 200) {
      ElMessage.success("批改提交成功！");
    } else {
      ElMessage.error(res.message || "批改提交失败");
    }
  } catch {
    ElMessage.error("批改提交出错");
  } finally {
    submitting.value = false;
  }
};

onMounted(fetchPaperList);
</script>

<style scoped>
.flex {
  display: flex;
}
</style>

<style scoped>
.flex {
  display: flex;
}
</style> 